package com.toune.villager.model

import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.RxSPTool
import com.toune.dltools.http.DLHttp
import com.toune.dltools.http.GsonBinder
import com.toune.dltools.http.IBaseCallBack
import com.toune.dltools.http.IDLHttpCallBack
import com.toune.dltools.ui.DLBaseViewModel
import com.toune.villager.Api
import com.toune.villager.AppContant
import com.toune.villager.activity.MainActivity
import com.toune.villager.bean.LoginBean
import com.toune.villager.bean.VerifyCodeImgBean

class LoginModel : DLBaseViewModel() {

    val verifyCodeImg = MutableLiveData<VerifyCodeImgBean>()
    val loginError = MutableLiveData<Int>()
    fun login(context: Context, userName: String, psw: String, code: String, uuid: String) {
        loadingSate.postValue(true)
        DLHttp.post(Api.LoginUrl)
            .add("username", userName)
            .add("password", psw)
            .add("code", code)
            .add("uuid", uuid)
            .buildByJson(object : IDLHttpCallBack<LoginBean>() {
                override fun success(t: LoginBean) {
                    loadingSate.postValue(false)
                    IBaseCallBack.headerMap["Authorization"] = "Bearer ${t.token}"
                    RxSPTool.putString(context, AppContant.SP_TOKEN, t.token)
                    RxActivityTool.skipActivityAndFinish(context, MainActivity::class.java)
                }

                override fun error(code: Int, err: String?) {
                    super.error(code, err)
                    loginError.postValue(code)
                    loadingSate.postValue(false)
                }
            })
    }

    fun getCaptchaImage() {
        DLHttp.get(Api.CaptchaImgUrl)
            .build(object : IDLHttpCallBack<VerifyCodeImgBean>() {
                override fun success(t: VerifyCodeImgBean) {
                    verifyCodeImg.postValue(t)
                }
            })
    }
}